package djrelay_server;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ConnectionHandler implements Runnable {
  private final Socket socket;
  public BufferedReader mBufferedReader;
  public PrintWriter mPrintWriter;
  public String testInput = "Hello";
  
  public ConnectionHandler(Socket socket) {
    this.socket = socket;
    Logger.getLogger(DJRelay_ServerFE.class.getName()).log(Level.INFO, "Socket instance created");
  }
  
  @Override
  public void run() {
    try {
      handleConnection(socket);
    } catch(IOException ioe) {
      System.err.println("IOException: " + ioe);
    }
  }
  
  public void handleConnection(Socket socket) throws IOException{ 
    // Do something with socket
      
      int fileSize = 3989727;      // hard code file size - need to remove this garbage
      int bytesRead;
      int current;
      
      Logger.getLogger(DJRelay_ServerFE.class.getName()).log(Level.INFO, "HandleConnection Routine invoked");
//      mBufferedReader = SocketUtil.getReader(socket);
//      mPrintWriter = SocketUtil.getWriter(socket);
//      testInput = mBufferedReader.readLine();
//      Logger.getLogger(DJRelay_ServerFE.class.getName()).log(Level.INFO, "testInput = " + testInput);

      byte[] mByteArray = new byte[fileSize];
      InputStream is = socket.getInputStream();
      FileOutputStream fos = new FileOutputStream("Client_01 Badge.mp3");
      BufferedOutputStream bos = new BufferedOutputStream(fos);
      bytesRead = is.read(mByteArray, 0, mByteArray.length);
      current = bytesRead;
      
      do {
          bos.write(mByteArray, 0, 1024);
          bytesRead = is.read(mByteArray, 0, (mByteArray.length - current));
          Logger.getLogger(DJRelay_ServerFE.class.getName()).log(Level.INFO, "mByteArray[1] = " + mByteArray[1]);  
          Logger.getLogger(DJRelay_ServerFE.class.getName()).log(Level.INFO, "bytesRead = " + bytesRead);
          if (bytesRead > -1){
              current += bytesRead;
              Logger.getLogger(DJRelay_ServerFE.class.getName()).log(Level.INFO, "current = " + current);
          }
      } while (bytesRead > 0);
      Logger.getLogger(DJRelay_ServerFE.class.getName()).log(Level.INFO, "While loop exited");      
//      bos.write(mByteArray, 0, current);
      Logger.getLogger(DJRelay_ServerFE.class.getName()).log(Level.INFO, "Buffered Output Stream Written");      
      bos.flush();
      bos.close();
  }
}
